﻿// Copyright  (c) 2011, The Outercurve Foundation. 
// The software is licensed under the New BSD License (the "License"); 
// you may not use the software except in compliance with the License. 

using System;

[assembly: CLSCompliant(false)]
namespace NMTopProtocols
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using Microsoft.NetworkMonitor;
    using Microsoft.NetworkMonitor.Automation;
    using System.Diagnostics;

    /// <summary>
    /// Launcher for NmTopProtocols
    /// </summary>
    [CLSCompliant(true)]
    public static class Program
    {
        /// <summary>
        /// Returned by API functions when they are successful
        /// </summary>
        private const ulong ERROR_SUCCESS = 0;

        /// <summary>
        /// Used to signal the API has been loaded
        /// </summary>
        private static bool initialized;

        /// <summary>
        /// Simple Expert Example to just spit out command line arguments.
        /// </summary>
        /// <param name="args">arguments from Netmon</param>
        [STAThread]
        public static void Main(string[] args)
        {
            //try
            //{
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                // Load API
                try
                {
                    initialized = Program.InitializeNMAPI();
                }
                catch (BadImageFormatException)
                {
                    MessageBox.Show("There was an error loading the NMAPI.\n\nPlease ensure you have the correct version installed for your platform.", "NMAPI Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                }
                catch (DllNotFoundException)
                {
                    MessageBox.Show("There was an error loading the NMAPI DLL.\n\nPlease ensure you have Network Monitor 3.3 installed or try rebooting.", "NMAPI Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                }

                if (initialized)
                {
                    CommandLineArguments commandReader = new CommandLineArguments();
                    if (commandReader.ParseCommandLineArguments(args))
                    {
                        Application.Run(new TopProtocols(commandReader));
                    }
                    else
                    {
                        MessageBox.Show(commandReader.LastErrorMessage + "\n\n" + CommandLineArguments.GetUsage("NmTopProtocols"), "Usage Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                    }

                    CloseNMAPI();
                }
            /*}
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "General Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            }*/
        }

        #region API Initialization and Cleanup
        /// <summary>
        /// Called to close the Network Monitor API when we're done
        /// </summary>
        private static void CloseNMAPI()
        {
            ulong errno = NetmonAPI.NmApiClose();
            if (errno != ERROR_SUCCESS)
            {
                Debug.WriteLine("Error unloading NMAPI Error Number = " + errno);
            }
        }

        /// <summary>
        /// Takes care of initializing the Network Monitor API
        /// </summary>
        /// <returns>true on success</returns>
        private static bool InitializeNMAPI()
        {
            // Initialize the NMAPI          
            NM_API_CONFIGURATION apiConfig = new NM_API_CONFIGURATION();
            apiConfig.Size = (ushort)System.Runtime.InteropServices.Marshal.SizeOf(apiConfig);
            ulong errno = NetmonAPI.NmGetApiConfiguration(ref apiConfig);
            if (errno != ERROR_SUCCESS)
            {
                MessageBox.Show("Failed to Get NMAPI Configuration Error Number = " + errno, "NMAPI Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                return false;
            }

            // Set possible configuration values for API Initialization Here
            ////apiConfig.CaptureEngineCountLimit = 4;

            errno = NetmonAPI.NmApiInitialize(ref apiConfig);
            if (errno != ERROR_SUCCESS)
            {
                MessageBox.Show("Failed to Initialize the NMAPI Error Number = " + errno, "NMAPI Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                return false;
            }

            return true;
        }
        #endregion
    }
}
